package top.dreamlove.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    /**
     * 获取HttpURLConnection文件对象
     */

    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        return (HttpURLConnection) httpUrl.openConnection();
    }

    /**
     * 获取文件名称
     */
    public static String getHttpFileName(String url){
        if(url == null || url.isEmpty()) return "";
        int len = url.lastIndexOf("/");
        return url.substring(len + 1);
    }

    /**
     * 分块下载
     * @param url URL
     * @param start 开始点
     * @param end  结束点
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url,long start,long end) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        System.out.println( Thread.currentThread().getName() +"下载的开始区间是"+ start  +",结束区间是" + end);

        if(end != 0){
            //设置下载区间
            httpURLConnection.setRequestProperty("RANGE","bytes="+ start  +"-" + end);
        }else {
            // Range:bytes=500-表示下载从500开始到文件结束这部分的内容
            httpURLConnection.setRequestProperty("RANGE","bytes="+ start  +"-");
        }
        return httpURLConnection;
    }

    //获取文件大小
    public static long getHttpURLContentLength(String url) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        int contentLength = httpURLConnection.getContentLength();
        httpURLConnection.disconnect();
        return contentLength;
    }
}
